import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '../layout/Layout.vue'
//import CaseIndex from '../views/case/Index.vue'
import Login from '../views/Login.vue'
import { getToken} from '../utils/token';
const routes: Array<RouteRecordRaw> = [ 
  {
    path: '/',
    name: 'Home',
    redirect:"/case",
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录', icon: 'el-icon-s-tools', dotNeedLogin: true },
    component: Login
  },
  {
    path: '/profile',
    component: Layout,
    meta: { title: '个人资料' },
    children: [
      {
        path: '',
        name: 'Profile',
        meta: { title: '个人资料' },
        component: () => import('../views/Profile.vue')        
      }
    ]
  },
  {
    path: '/case',
    component: Layout,
    meta: { title: '档案管理' },
    children: [
      {
        path: '',
        name: 'CaseIndex',
        //component: CaseIndex,
        meta: { title: '档案管理' },
        component: () => import(/* webpackChunkName: "about" */ '../views/case/Index.vue')        
      },
      {
        path: 'detail',
        name: 'CaseDetail',
        meta: { title: '档案详情' },
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/case/Detail.vue')
      }
    ]
  },
  {
    path: '/file',
    component: Layout,
    meta: { title: '文件管理' },
    children: [
      {
        path: 'template',
        name: 'FileIndex',
        meta: { title: '模板管理' },
        component: () => import('../views/file/Index.vue')        
      }
    ]
  },
  {
    path: '/team',
    component: Layout,
    meta: { title: '团队管理' },
    children: [
      {
        path: 'role',
        name: 'RoleIndex',
        meta: { title: '角色管理' },
        component: () => import('../views/role/Index.vue')        
      },
      {
        path: 'user',
        name: 'UserIndex',
        meta: { title: '用户管理' },
        component: () => import('../views/user/Index.vue')        
      }
    ]
  },
  {
    path: '/setting',
    component: Layout,
    meta: { title: '系统设置' },
    children: [
      {
        path: '',
        name: 'SettingIndex',
        meta: { title: '系统设置' },
        component: () => import('../views/setting/Index.vue')        
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  getToken().then((token)=>{
    
    if(!token && !to.meta.dotNeedLogin){
      next('/login');
      return
    }
    if (to.matched.length === 0 || !to.name) { 
      next('/');
    }
    /* 路由发生变化修改页面title */
    if (to.meta.title) {
      document.title = to.meta.title
    }
    next()
  })
  
})

export default router
